package com.cim.service.impl;

import com.cim.config.GlobalConfig;
import com.cim.dao.VideoDao;
import com.cim.pojo.Video;
import com.cim.service.VideoService;
import com.cim.storage.StorageService;
import com.cim.utils.CharUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class VideoServiceImpl implements VideoService {
    @Autowired
    private VideoDao videoDao;
    @Autowired
    StorageService storageService;
    public List<Video> findVideos(Video video) {
        List<Video> list=videoDao.findVideos(video);
        return list;
    }

    public Video getVideo(String id) {
        return videoDao.getVideo(id);
    }

    public int addVideos(List<Video> videos) {
        int count=0;
        for(Video v:videos){
            count+=videoDao.addVideo(v);
        }
        return count;
    }

    public Video addVideo(Video video) {
        String id= CharUtil.getUUID(10); //视频分配ID
        video.setVideoId(id);          //分配ID
        if(video.getLive().equals("true")){
            //是直播，分配直播间ID
            video.setPlayBack(0);   //直播未开始
            video.setPushAddress(GlobalConfig.RTMPServiceAddress);
            video.setPushKey(id+"?key="+CharUtil.getUUID(10));
            video.setVideoAddress(GlobalConfig.RTMPServiceAddress+id);
            video.setCreateTime(video.getStartTime());      //直播课程,更新时间为直播开始时间
        }else{
            String currentTime=String.valueOf(System.currentTimeMillis()/1000);
            //视频课程,课时创建时间为现在
            video.setCreateTime(currentTime);
            video.setPlayBack(-1);
            video.setPushAddress("");
            video.setPushKey("");

        }
        videoDao.addVideo(video);
        return video;
    }

    public int deleteVideo(String id) {
        return videoDao.deleteVideo(id);
    }

    public int updateVideo(Video video) {
        return videoDao.updateVideo(video);
    }

    @Override
    public int deleteByCourseId(String courseId) {
        //删除课程产生的对应文件
        Video video=new Video();
        video.setCourseId(courseId);
        List<Video> list=videoDao.findVideos(video);
        for(Video v:list){
            if(v.getPlayBack()==-1||v.getPlayBack()==2){    //课程状态为视频 或者直播已结束 有回放视频 时执行删除
                storageService.delete(v.getVideoAddress());
            }

        }
        return videoDao.deleteByCourseId(courseId);
    }
}
